﻿#region  文件信息
// ---------------------------------------------------------------------------------------
// <copyright file="OneFormsAuthentication.cs" company="">
// 作者：李帅伦
// </copyright>
// <summary>
// 类型简介：
// 类型详细：OneFormsAuthentication.cs
// 创建时间：2014-09-04 16:29
// 修改时间：2014-09-04 16:29
// </summary>
// ---------------------------------------------------------------------------------------
#endregion
namespace WebCommon.Extensions
{
    using System;
    using System.Web;
    using System.Web.Security;

    public class ExAuthentication
    {
        /// <summary>
        /// 票证的版本号
        /// </summary>
        public int Version { get; set; }

        /// <summary>
        /// 票证发出时的本地日期和时间
        /// </summary>
        public DateTime IssueDate { get; set; }
        /// <summary>
        /// 票证过期时的本地日期和时间
        /// </summary>
        public DateTime Expiration { get; set; }
        /// <summary>
        /// 如果票证将存储在持久性 Cookie 中（跨浏览器会话保存），则为 true；否则为 false。如果该票证存储在 URL 中，将忽略此值。Cookie
        /// </summary>
        public bool IsPersistent { get; set; }

        /// <summary>
        /// 获取用于存储 Forms 身份验证票证的 Cookie 名称。
        /// </summary>
        public string FormsCookieName { get; private set; }
        /// <summary>
        /// 构造函数
        /// </summary>
        public ExAuthentication()
        {
            this.Version = 1;
            this.IssueDate = DateTime.Now;
            this.Expiration = DateTime.Now.AddMinutes(7);
            this.IsPersistent = true;
        }
        /// <summary>
        /// 创造一个FormsAuthenticationTicket
        /// </summary>
        /// <param name="name">与票证关联的用户名</param>
        /// <param name="userData">存储在票证中的用户特定的数据</param>
        public void CreateAuthenticate(string name, string userData)
        {
            try
            {
                var ticket = new FormsAuthenticationTicket(
                    this.Version,
                    name,
                    this.IssueDate,
                    this.Expiration,
                    this.IsPersistent,
                    userData);
                var hachTicket = FormsAuthentication.Encrypt(ticket);
                var httpCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hachTicket);
                this.FormsCookieName = FormsAuthentication.FormsCookieName;
                System.Web.HttpContext.Current.Response.Cookies.Add(httpCookie);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}